package com.kedacom.general.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class UdpServer extends Thread {

    @Autowired
    private UdpServerlInitalizer udpServerInitalizer;

    @Value("${interphone.port}")
    private int port;
    @Override
    public void run() {
        log.info("Building server...");
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 100)
                    .option(ChannelOption.RCVBUF_ALLOCATOR,
                            new FixedRecvByteBufAllocator(65535))
                    .handler(udpServerInitalizer);
            b.bind(port).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        log.info("Building server finished!");
    }

    @PostConstruct
    public void init(){
        log.info("start server");
        this.start();
    }
}
